package com.sys.controller;

import com.sys.bean.Admin;
import com.sys.bean.RespBean;
import com.sys.exception.SysException;
import com.sys.service.AdminService;
import com.sys.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

@CrossOrigin
@Controller
@RestController
public class AdminController {
    //登录
    @Autowired
    private AdminService adminService;
    @ResponseBody
    @PostMapping("/login")
    public RespBean login(String username, String password, String captchaInput) throws SysException {
        //获取session，获取session中的验证码
        //String captcha = (String)session.getAttribute("captcha");
        ////忽略大小写判断
        //if(!captchaInput.equalsIgnoreCase(captcha)) {
        //    return RespBean.error("验证码错误，请确认后重新登录");
        //}
        //判断用户名和密码是否正确
        Admin admin = adminService.login(username, password);
        //登录成功生成jwt
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", admin.getId());
        map.put("username", admin.getUsername());
        String jwt = JwtUtil.generateJwt(map);
        return RespBean.ok("登录成功", jwt);
    }
    //注销
    @ResponseBody
    @GetMapping("/logout")
    public RespBean logout(HttpSession session){
        //让session失效
        session.invalidate();
        //返回注销成功的信息
        return RespBean.error("退出成功");
    }
    //验证码
    //@GetMapping("/captcha")
    //public void captcha(HttpServletResponse response, HttpSession session) throws IOException {
    //    //生成验证码对象
    //    LineCaptcha captcha = new LineCaptcha(120, 38, 4, 20);
    //    //保存验证码到session
    //    session.setAttribute("captcha", captcha.getCode());
    //    //返回验证码给浏览器
    //    captcha.write(response.getOutputStream());
    //    response.getOutputStream().close();
    //}
}
